XM.lang.namespace('XM.common');

/**
 * 资源管理器
 * 集中管理图片，音乐等外部资源文件
 */
XM.common.ResourceManager = {
    _resourceConfig: GLOBAL_CONFIG['resource'],
    _resourceCount: -1,
    _unCompleteImageCount: -1,
    _resource: {
        image: {}, sound: {}
    },

    /**
     * 资源预载入
     * 目前只支持图片资源
     */
    preLoad: function () {
        var rc = this._resourceConfig;
        var count = 0;

        for (var p in rc['image']) {
            count += 1;
            var path = rc['image'][p];
            var img = new Image();
            img.onload = (function (p) {
                return function (ev) {
                    XM.common.ResourceManager._unCompleteImageCount -= 1;
                    XM.common.ResourceManager._resource['image'][p] = {status: true, entity:this};
                }
            })(p);
            img.src = path;
        }

        this._resourceCount = this._unCompleteImageCount = count;
    },

    /**
     * 获得资源
     * @param key {string}
     * @param type {string}
     */
    getResource: function (key, type) {
        var type = type || 'image';
        return this._resource[type][key]['entity'];
    },

    /**
     * 资源是否与加载完成
     * @return {boolean}
     */
    isReady: function () {
        return this._unCompleteImageCount == 0;
    },

    /**
     * 获得载入百分比
     * @return {number}
     */
    getPercent: function () {
        return Math.floor(this._resourceCount / 100);
    }
};